package cn.sdhuijin.vms.webservice;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.jws.WebService;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sdhuijin.vms.dao.ICarDao;
import cn.sdhuijin.vms.dao.ICardDao;
import cn.sdhuijin.vms.dao.IPersonDao;
import cn.sdhuijin.vms.dao.IReaderDao;
import cn.sdhuijin.vms.model.Car;
import cn.sdhuijin.vms.model.Card;
import cn.sdhuijin.vms.model.Person;
import cn.sdhuijin.vms.model.Reader;
import cn.sdhuijin.vms.service.IControllerService;
import cn.sdhuijin.vms.service.IRecordService;

@WebService(endpointInterface = "cn.sdhuijin.vms.webservice.IRecordWebService")
public class RecordWebService implements IRecordWebService {
	final Logger logger = LoggerFactory.getLogger(RecordWebService.class);
	private Map<String, Date> recordRequestMap = new HashMap<String, Date>();
	@Inject
	private IControllerService controllerService;
	@Inject
	private IRecordService recordService;
	@Inject
	private IReaderDao readerDao;
	@Inject
	ICardDao cardDao;
	@Inject
	IPersonDao personDao;
	@Inject
	ICarDao carDao;

	public RecordWebService() {

	}

	@Override
	public List<Controller> getControllers() {
		logger.info("控制器信息被获取。");
		List<Controller> cntrollers = new ArrayList<Controller>();
		List<cn.sdhuijin.vms.model.Controller> ctrlsraw = controllerService
				.list();
		for (cn.sdhuijin.vms.model.Controller c : ctrlsraw) {
			logger.debug("controller:", c);
			Controller ctrl = new Controller(c.getSn(), c.getIp());
			cntrollers.add(ctrl);
		}
		return cntrollers;
	}

	@Override
	public RecordResult record(RecordRequest request) throws ParseException {

		Reader reader = readerDao.findByControllerSnAndNumber(
				Integer.parseInt(request.getControllerSn()),
				Integer.parseInt(request.getReaderNumber()));
		logger.debug("reader:{}", reader);
		Card card = this.cardDao.findByNumber(Integer.parseInt(request
				.getCardNumber()));
		logger.debug("card:{}", card);
		RecordResult rr = new RecordResult();
		rr.setOpen(false);
		if (card != null) {
			Date date;
			if (!isRepeat(request)) {
				try {
					try {
						date = DateUtils.parseDate(request.getDateString(),
								"yyyy-MM-dd HH:mm:ss");
						System.out.println("aaa");
					} catch (Exception e) {
						System.out.println("bbb");
						date=DateUtils.parseDate(request.getDateString(),
								"yyyy/M/dd HH:mm:ss");
					}
					logger.debug("date:{}", date);
					switch (card.getType()) {
					case CAR:
						this.addCarRecord(reader, card, date);
						rr.setOpen(true);
						rr.setDoorNumber(reader.getDoorNumber());
						logger.info("开门:{}", reader.getDoorNumber());
						break;
					case PERSON:
						this.addPersonRecord(reader, card, date);
						break;
					}
				} catch (Exception e) {
					logger.error("未知的错误：{}", e.toString());
				}
			}
		} else {
			logger.warn("没有注册的卡号：{}，刷卡位置：{},{}", request.getCardNumber(),
					request.getControllerSn(),
					reader.getPosition() + request.getReaderNumber());
		}
		return rr;
	}

	private void addPersonRecord(Reader reader, Card card, Date date) {
		Person person = personDao.findByCardNumber(card.getNumber());
		logger.debug("person:{}", person);
		if (person != null) {
			if ("in".equals(reader.getPosition())) {
				recordService.addIn(person, reader.getController()
						.getOrganization(), date);
			} else {
				recordService.addOut(person, reader.getController()
						.getOrganization(), date);
			}
		} else {
			logger.warn("未绑定的卡:{}", card);
		}

	}

	private void addCarRecord(Reader reader, Card card, Date date) {
		Car car = carDao.findByCardNumber(card.getNumber());
		logger.debug("car:{}", car);
		if (car != null) {
			if ("in".equals(reader.getPosition())) {
				recordService.addIn(car, reader.getController()
						.getOrganization(), date);
			} else {
				recordService.addOut(car, reader.getController()
						.getOrganization(), date);
			}
		} else {
			logger.warn("未绑定的卡:{}", card);
		}
	}

	private boolean isRepeat(RecordRequest request) throws ParseException {
		Boolean result = false;
		String key = request.getCardNumber();
		Date thisDate ;
		try {
			thisDate = DateUtils.parseDate(request.getDateString(),
					"yyyy-MM-dd HH:mm:ss");
			System.out.println("aaa");
		} catch (Exception e) {
			System.out.println("bbb");
			thisDate=DateUtils.parseDate(request.getDateString(),
					"yyyy/M/dd HH:mm:ss");
		}
		if (recordRequestMap.containsKey(key)) {
			Date lastDate = recordRequestMap.get(key);
			Long dif = thisDate.getTime() - lastDate.getTime();
			if (dif <= 60000) {
				logger.debug("重复：csn:{},rn:{},cn:{}",
						request.getControllerSn(), request.getReaderNumber(),
						request.getCardNumber());
				result = true;
			}
		}
		recordRequestMap.put(key, thisDate);
		return result;
	}

}
